package com.cyy.demo.common;


import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * controller异常处理
 */

@Slf4j
@ControllerAdvice
public class GlobalControllerAdvice {


    //默认异常处理页面
    public static final int ERROR_CODE = 500;
    public static final String ERROR_MSG = "服务器异常";

    //非法参数
    public static final String ARG_ERROR_MSG = "非法参数";

    /**
     * 默认异常处理方法,返回异常请求路径和异常信息
     */
    @ResponseBody
    @ExceptionHandler(value = RuntimeException.class)
    public String defaulErrorHandler(HttpServletRequest request, RuntimeException e) throws  RuntimeException{
        log.error("发生异常:{}",e);
        return new Result(HttpStatus.INTERNAL_SERVER_ERROR.value(),ERROR_MSG,e.getMessage()).toJson();
    }

    /**
     * 入参验证不通过处理
     */
    @ResponseBody
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public String argErrorHandler(HttpServletRequest request, MethodArgumentNotValidException e) throws  RuntimeException{
        log.error("非法参数:{}",e.getMessage());
        return new Result(HttpStatus.BAD_REQUEST.value(),ARG_ERROR_MSG,e.getBindingResult().getFieldError().getDefaultMessage()).toJson();
    }
}
